import { ar } from "element-plus/es/locale";

/*
 * @Author: upp24 1246815351@qq.com
 * @Date: 2023-07-05 17:57:14
 * @LastEditors: upp24 1246815351@qq.com
 * @LastEditTime: 2023-07-06 09:55:51
 * @FilePath: /pure-admin-thin-i18n/src/utils/area.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
interface Area {
  code: string;
  name: string;
  cities?: Record<string, Area>;
}
/**根据地区编码查找地区名称 */
export function findAreaByCode(
  data: Record<string, Area>,
  code: string
): Area | undefined {
  if (!data || typeof data !== "object" || !code || typeof code !== "string") {
    // 参数校验：如果传入的参数不符合预期的格式和类型，则返回 undefined
    return undefined;
  }
  try {
    for (const key in data) {
      const area = data[key];
      if (area.code === code) {
        return area;
      }
      if (area.cities) {
        const subArea = findAreaByCode(area.cities, code);
        if (subArea) {
          return subArea;
        }
      } else if (typeof area === "string" && key == code) {
        return {
          code: key,
          name: area
        };
      }
    }
  } catch (error) {
    // 错误处理：如果函数执行过程中出现异常，则返回 undefined
    console.error(error);
    return undefined;
  }
  // 如果未找到匹配的省市区信息，则返回 undefined
  return undefined;
}
/**根据地区名称查找地区编码 */
export function findAreaByName(
  data: Record<string, Area>,
  name: string
): Area | undefined {
  if (!data || typeof data !== "object" || !name || typeof name !== "string") {
    // 参数校验：如果传入的参数不符合预期的格式和类型，则返回 undefined
    return undefined;
  }
  try {
    for (const key in data) {
      const area = data[key];
      if (area.name === name) {
        return area;
      }
      if (area.cities) {
        const subArea = findAreaByName(area.cities, name);
        if (subArea) {
          return subArea;
        }
      } else if (typeof area === "string" && area === name) {
        return {
          code: key,
          name: area
        };
      }
    }
  } catch (error) {
    // 错误处理：如果函数执行过程中出现异常，则返回 undefined
    console.error(error);
    return undefined;
  }
  // 如果未找到匹配的省市区信息，则返回 undefined
  return undefined;
}
